<template>
	<ToolbarItemContainer :iconFile="fileIcon" title="文件" :iconWidth="isUniFrameWork ? '32px' : '20px'"
		:iconHeight="isUniFrameWork ? '25px' : '18px'" :needDialog="false" @onIconClick="onIconClick">
		<div :class="['file-upload', !isPC && 'file-upload-h5']">
			<input ref="inputRef" title="文件" type="file" data-type="file" accept="*" @change="sendFileMessage">
		</div>
	</ToolbarItemContainer>
</template>
<script lang="ts" setup>
	import TUIChatEngine, {
		TUIChatService,
		TUIStore,
		StoreName,
		IConversationModel,
		SendMessageParams,
		SendMessageOptions,
	} from '@tencentcloud/chat-uikit-engine';
	import { ref } from '../../../../adapter-vue';
	import ToolbarItemContainer from '../toolbar-item-container/index.vue';
	import fileIconLight from '../../../../assets/icon/file-light.svg';
	import fileIconDark from '../../../../assets/icon/file-dark.svg';
	import { isPC, isUniFrameWork } from '../../../../utils/env';
	import { isEnabledMessageReadReceiptGlobal } from '../../utils/utils';
	import OfflinePushInfoManager, { IOfflinePushInfoCreateParams } from '../../offlinePushInfoManager/index';
	import TUIChatConfig from '../../config';
	const fileIcon = TUIChatConfig.getTheme() === 'dark' ? fileIconDark : fileIconLight;
	const inputRef = ref();
	const currentConversation = ref<IConversationModel>();

	TUIStore.watch(StoreName.CONV, {
		currentConversation: (conversation : IConversationModel) => {
			currentConversation.value = conversation;
		},
	});


	const fileData = ref({
		files: [
			// {
			// 	name: '', // 文件名
			// 	size: 10, //本地文件大小
			// 	type: '', //文件类型
			// 	path: '', //本地文件路径
			// 	lastModified: '', // 修改时间
			// },
		]

	}
	)
	const onIconClick = () => {
		const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
		if (uni.getSystemInfoSync().platform == 'ios') {
			lemonjkFileSelect.showPicker({
				pathScope: "/Download",
				mimeType: "*/*",
				utisType: ["public.data"],
				multi: 'yes'
			}, result => {
				const filesres = result.files.map(item => ({
					// lastModified: item.timestamp,
					type: item.fileExtension,
					size: item.fileSize,
					name: item.fileName,
					path: item.filePath
				}));
				fileData.value.files = [...fileData.value.files, ...filesres];
				let promise = TUIChatService.sendFileMessage({
					payload: {
						file: fileData.value
					},
				});
				promise.then((imResponse) => {
					console.log('成功', imResponse.data.message)
				});
				promise.catch((error) => {
					console.log(error, '捕获异常')
				});
			})
		} else {
			lemonjkFileSelect.showNativePicker({
				pathScope: "/Download",
				mimeType: "*/*",
				utisType: ["public.data"],
				multi: 'yes'
			}, result => {
				const filesres = result.files.map(item => ({
					// lastModified: item.timestamp,
					type: item.fileExtension,
					size: item.fileSize,
					name: item.fileName,
					path: item.filePath
				}));
				fileData.value.files = [...fileData.value.files, ...filesres];
				let promise = TUIChatService.sendFileMessage({
					payload: {
						file: fileData.value
					},
				});
				promise.then((imResponse) => {
					console.log('成功', imResponse.data.message)
				});
				promise.catch((error) => {
					console.log(error, '捕获异常')
				});
			})
			
			
			// const AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
			// console.log('AfDocument',AfDocument)
			// AfDocument.openMode({
			// 	size: '10', //选择总数量
			// 	paths: ['/storage/emulated/0/Download', '/storage/emulated/0/A',],   //自定义选择目录
			// 	isDown: true,//是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
			// 	types: [{
			// 		name: '文档',
			// 		value: ["doc", "wps", "docx", "xls", "xlsx", "pdf", "ppt"]
			// 	}, {
			// 		name: '视频',
			// 		value: ["mp4"]
			// 	}, {
			// 		name: '音乐',
			// 		value: ['mp3', 'flac']
			// 	}, {
			// 		name: '图片',
			// 		value: ['jpg', 'png']
			// 	}]
			// }, (res) => {
			// 	console.log('返回的数据', res)
			// 	const filesres = res.res.map(file => ({
			// 		lastModified: file.timestamp,
			// 		type: file.type,
			// 		size: Number(file.size.match(/^\d+/)[0] * 1024),
			// 		name: file.name,
			// 		path: file.pathHolp
			// 	}));
			// 	fileData.value.files = [...fileData.value.files, ...filesres];
			// 	console.log('传递的参数:', fileData.value);
			// 	if (filesres) {
			// 		let promise = TUIChatService.sendFileMessage({
			// 			payload: {
			// 				file: fileData.value
			// 			},
			// 		});
			// 		promise.then((imResponse) => {
			// 			console.log('成功', imResponse.data.message)
			// 		});
			// 		promise.catch((error) => {
			// 			console.log(error, '捕获异常')
			// 		});
			// 	}
			// })
		}





		// let promise = TUIChatService.sendFileMessage({
		//  payload: {
		//    file: fileData.value
		//  },
		// });
		// promise.then((imResponse) =>{
		// 	console.log('res',imResponse.data)
		// });
		// promise.catch((error) => {
		// 	console.log(error,'捕获异常')
		// });




		// if (isUniFrameWork) {
		//   return;
		// } else {
		//   inputRef?.value?.click && inputRef?.value?.click();
		// }
	};

	const sendFileMessage = (e : any) => {
		// if (e?.target?.files?.length <= 0) {
		// 	return;
		// }
		const options = {
			to:
				currentConversation?.value?.groupProfile?.groupID
				|| currentConversation?.value?.userProfile?.userID,
			conversationType: currentConversation?.value?.type,
			payload: {
				file: fileData.value,
			},
			needReadReceipt: isEnabledMessageReadReceiptGlobal(),
		} as SendMessageParams;
		const offlinePushInfoCreateParams : IOfflinePushInfoCreateParams = {
			conversation: currentConversation.value,
			payload: options.payload,
			messageType: TUIChatEngine.TYPES.MSG_FILE,
		};
		const sendMessageOptions : SendMessageOptions = {
			offlinePushInfo: OfflinePushInfoManager.create(offlinePushInfoCreateParams),
		};

		TUIChatService.sendFileMessage(options, sendMessageOptions);
		e.target.value = '';
	};
</script>
<style lang="scss" scoped>
	@import "../../../../assets/styles/common";
</style>